package yun.web.activerecord.ext;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import yun.web.enjoy.template.Directive;
import yun.web.enjoy.template.Env;
import yun.web.enjoy.template.expr.ast.Expr;
import yun.web.enjoy.template.io.Writer;
import yun.web.enjoy.template.stat.Scope;
import yun.web.activerecord.ActiveRecordException;
import yun.web.activerecord.SqlPara;

public class PDirective extends Directive {
    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        StringBuilder sb = (StringBuilder) ReflectUtil.getFieldValue(this.stat, "content");

        if (sb == null) throw new ActiveRecordException("检查p指令内容是否没写~, 请");

        String[] split = sb.toString().split("\n");
        for (String s : split) {
            if (StrUtil.isBlank(s)) {
                throw new ActiveRecordException("来自 p 指令的吐槽, 空荡荡的sql片段不要放在我的身体里");
            } else if (!s.contains("?")) {
                throw new ActiveRecordException("来自 p 指令的吐槽, 不带占位符的sql片段不要放在我的身体里");
            }
        }


        //传入指令的参数列表
        Expr[] directory_params = exprList.getExprArray();
        SqlPara sqlPara = (SqlPara) scope.get("_SQL_PARA_");

        int i = 0;
        for (String it : split) {
            Expr name = directory_params[i++];
            Object value = name.eval(scope);
            if (value != null) {
                sqlPara.addPara(value);
                write(writer, it);
                write(writer, "\n");
            }
        }


    }

    @Override
    public boolean hasEnd() {
        return true;
    }
}
